import '../style/register.css'
import TopComponent from '../../components/topComponent'
import { Button, Input, Toast, Form } from 'react-vant'
import type { loginType } from '../../types/login'
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { handleAddUser,handleSendEmail } from '../../utils/api'
const RegisterPage: React.FC = () => {
    const [formValues, setFormValues] = useState<loginType>({ email: '' });
    const [form] = Form.useForm();
    const navigate = useNavigate()
    const [isLoading, setIsLoading] = useState(false)
    const YanZhen = (value: string) => {
        const guize = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
        const values = guize.test(value)
        if (values) {
            return true
        } else {
            return false
        }
    }
    const goBack = () => {
        navigate('/onboarding')
    }
    const [status,setStatus] = useState(false)
    const onFinish = async () => {
        if (!formValues.email) return
        try {
            setIsLoading(true)
            Toast.loading({
                message:"正在注册中...",
                forbidClick:true,
                duration:0,
                loadingType:"circular"
            })
            const params = {
                email: formValues.email
            }
            const  res = await handleAddUser(params)
            await handleSendEmail(params)
            Toast.clear()
            if (res.data.code === 200) {
                Toast.success({
                    message:"注册成功",
                    forbidClick:true,
                })
                setStatus(true)
            }else {
                // 显示错误提示，2秒后自动消失
               Toast.fail({
                message:res.data.message || '网络错误，请重试',
                forbidClick:true,
                duration:2000,
               })
            }
        } catch (err) {
            console.log(err,'err');
        } finally {
            setIsLoading(false)
        }
    }
    const onValuesChange = () => {
        const values = form.getFieldsValue()
        setFormValues(values)
    }
    useEffect(() => {
        if (status) {
          const timer = setTimeout(() => {
            navigate('/yanzheng',{state:{
                    email:formValues.email
                }}
            );
            setStatus(false); // 重置状态
          }, 2000);
          return () => clearTimeout(timer); // 清除定时器
        }
      }, [status, navigate]);
    return (
        <>
            <div className="parentBox">
                <TopComponent title="3" handleGoBack2={goBack} />
                {/* 表单 */}
                <div className="parentBox-login">
                    <Form
                        form={form}
                        onFinish={onFinish}
                        onValuesChange={onValuesChange}
                        footer={
                            <div style={{ margin: '16px 16px 0' }}>
                                <Button round nativeType='submit' type='primary' block
                                    loading={isLoading}
                                    disabled={!YanZhen(String(formValues.email))}
                                >
                                    继续
                                </Button>
                            </div>
                        }
                    >
                        <span className="parentBox-span">电子邮箱</span>
                        <Form.Item
                            name='email'
                            rules={[{ pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '请输入正确的邮箱' }]}
                        >
                            <Input placeholder='输入您的电子邮箱' className="parentBox-input" />
                        </Form.Item>
                    </Form>
                </div>

                <div className="parentBox-divider">
                    <span>或者</span>
                </div>
                <div className="third-party-login">
                    <Button className="phone-btn">
                        <img src="/images/phone.svg" alt="phone" />
                        使用手机注册
                    </Button>
                </div>
                <div className="register-link">
                    <span>你是不是已经有一个账号？</span>
                    <span className="register" onClick={() => navigate('/login')}>登录</span>
                </div>
            </div>
        </>
    )
}
export default RegisterPage